import { NextRequest, NextResponse } from 'next/server';
import { readCategories, writeCategories, generateId } from '@/lib/data';
import { verifyToken } from '@/lib/auth';
import { Category } from '@/types';

export async function GET() {
  try {
    const categories = readCategories();
    
    // 构建树形结构
    const buildTree = (parentId: string | null = null): Category[] => {
      return categories
        .filter(cat => cat.parentId === parentId)
        .map(cat => ({
          ...cat,
          children: buildTree(cat.id),
        }));
    };

    return NextResponse.json({ success: true, categories: buildTree() });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '获取分类失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const token = request.cookies.get('token')?.value;
    const decoded = verifyToken(token || '');
    
    if (!decoded || !decoded.isAdmin) {
      return NextResponse.json(
        { success: false, message: '需要管理员权限' },
        { status: 403 }
      );
    }

    const { name, parentId } = await request.json();

    if (!name) {
      return NextResponse.json(
        { success: false, message: '分类名称不能为空' },
        { status: 400 }
      );
    }

    const categories = readCategories();
    const parent = parentId ? categories.find(c => c.id === parentId) : null;
    
    const newCategory: Category = {
      id: generateId(),
      name,
      parentId: parentId || null,
      path: parent ? `${parent.path}/${name}` : name,
      level: parent ? parent.level + 1 : 1,
    };

    categories.push(newCategory);
    writeCategories(categories);

    return NextResponse.json({ success: true, category: newCategory });
  } catch (error) {
    return NextResponse.json(
      { success: false, message: '创建分类失败' },
      { status: 500 }
    );
  }
}

